const app = getApp();
import {insertLetterImage,insertLetter} from '../../../api/letter_v1'
import Notify from '@vant/weapp/notify/notify';
Page({
  data: {
    app: app,
    to:'',
    from:'',
    error: {
        to_show: false,
        to_message: "请输入to",
        from_show: false,
        from_message: "请输入from"
    },
    toolbarShow: true,   //工具栏是否显示(暂未控制显隐,此字段写死为true)
    toolbarContentShow: false,  //工具栏内容是否显示
	editorHeight:300,           //编辑器内容高度
    keyboardHeight: 0,          //键盘高度
    toolBarHeight: 96, // 工具栏高度
    toolbarContentHeight:530,     //工具栏内容高度
    iphoneXBottomHeight:0,      //iphoneX底部高度
    isIOS: false,          //用来标记是否是IOS
    toolbarType: "",     //当前选中的工具栏名称
    formats: {
      bold: false,
      italic: false,
      underline: false,
      header: "default",
      fontSize: "default",
      color: "#000000",
      align: "left",
      list: "",
      lineHeight: "1.3",
    },
    toolbar: {
      textformat: {
        style: [
          { key: "bold", icon: "icon-zitijiacu", text: "" }, //加粗
          { key: "italic", icon: "icon-zitixieti", text: "" }, //倾斜
          { key: "underline", icon: "icon-zitixiahuaxian", text: "" }, //倾斜
        ],
        title: [
          { key: "default", icon: "", text: "正文" }, //正文
          { key: "H1", icon: "icon-formatheader1" }, //H1
          { key: "H2", icon: "icon-formatheader2" }, //H2
          { key: "H3", icon: "icon-formatheader3" }, //H3
          { key: "H4", icon: "icon-formatheader4" }, //H4
        ],
        fontSize: [
					{ key: "default", icon: "", text: "默认" }, //18
					{ key: "20", icon: "", text: "20" }, //18
          { key: "18", icon: "", text: "18" }, //18
          { key: "16", icon: "", text: "16" }, //16
          { key: "14", icon: "", text: "14" }, //14
          { key: "12", icon: "", text: "12" }, //12
        ],
        color: [
          { key: "#FFFFFF", icon: "", text: "#FFFFFF" }, //白色
          { key: "#000000", icon: "", text: "#000000" }, //黑色
          { key: "#FF0000", icon: "", text: "#FF0000" }, //红色
          { key: "#FFFF00", icon: "", text: "#FFFF00" }, //黄色
          { key: "#87C120", icon: "", text: "#87C120" }, //绿色
          { key: "#403ED6", icon: "", text: "#403ED6" }, //蓝色
        ],
      },
      paragraph: {
        align: [
          { key: "left", icon: "icon-juzuoduiqi", text: "" }, //居左
          { key: "center", icon: "icon-juzhongduiqi", text: "" }, //居中
          { key: "right", icon: "icon-juyouduiqi", text: "" }, //居右
          { key: "justify", icon: "icon-liangduanduiqi", text: "" }, //两端对齐
        ],
        list: [
          { key: "bullet", icon: "icon-unordered-list1", text: "" }, //无序
          { key: "ordered", icon: "icon-ordered-list", text: "" }, //有序
          { key: "check", icon: "icon-check-box", text: "" }, //选择
        ],
        lineHeight: [
          { key: "1", icon: "", text: "1" },
          { key: "1.3", icon: "", text: "1.3" },
          { key: "1.5", icon: "", text: "1.5" },
          { key: "2", icon: "", text: "2" },
          { key: "3", icon: "", text: "3" },
        ],
      },
    },
  },

  onLoad(options) {
    const that = this
    const res = wx.getSystemInfoSync()
    const isIOS = res.platform === 'ios'
    const isIphoneX = (res.platform === 'devtools' || isIOS) && res.safeArea.top == 44
    const iphoneXBottomHeight=isIphoneX?34:0
    this.updatePosition(0)
    let keyboardHeight = 0
    wx.onKeyboardHeightChange(e => {
      if (e.height === keyboardHeight) return
      const duration = e.height > 0 ? e.duration * 1000 : 0
      keyboardHeight = e.height
      setTimeout(() => {
        wx.pageScrollTo({
          scrollTop: 0,
          success() {
            that.updatePosition(keyboardHeight)
            that.editorCtx.scrollIntoView()
          }
        })
      }, duration)
    })
    
  },
  updatePosition(keyboardHeight) {
    const toolbarHeight = 96
    const { windowHeight, platform } = wx.getSystemInfoSync()
    let editorHeight = keyboardHeight > 0 ? (windowHeight - keyboardHeight - toolbarHeight)*2 : windowHeight*2
    this.setData({ editorHeight, keyboardHeight })
  },
  onEditorReady() {
    const that = this;
    wx.createSelectorQuery()
      .select("#editor")
      .context(function (res) {
			that.editorCtx = res.context;
      })
      .exec();
  },
  //编辑器获取焦点
  onFocusEditor(){
    this.setData({
        toolbarContentShow:false,
        toolbarType:""
    })
  },
  //编辑器失去焦点
  onBlurEditor(e){
	console.log(e)
    // this.setData({
        
    // })
  },
  onStatusChangeEditor(e){
		const {detail}=e;
		let keys=Object.getOwnPropertyNames(detail);
		let initFormats={
			bold: false,
      italic: false,
      underline: false,
      header: "default",
      fontSize: "default",
      color: "#000000",
      align: "left",
      list: "",
      lineHeight: "1.3",
		}
		keys.forEach(item=>{
			if(item==='header'){
				initFormats.header='H'+detail[item]
			}
			else if(item==='color'){
				initFormats.color=detail[item].toUpperCase()
			}
			else{
				initFormats[item]=detail[item];
			}
		})
		this.setData({
			formats:initFormats
		})
  },
  onReady() {},
  onShow() {},
  onClickAction(e) {
    let key = e.currentTarget.dataset.key;
    this.editorCtx.blur();
    this.setData({
      toolbarType: key,
      toolbarContentShow: true,
    });
  },
	onClickEditorStyle(e){
        let that=this;
		const type=e.currentTarget.dataset.type;
		const value=e.currentTarget.dataset.value;
		switch (type) {
			case 'fontSize':
				//改变字体大小
				if(value!==this.data.formats.fontSize&&this.data.formats.header==='default'){
					//处理选择默认的数据
					if(value==='default'){
						this.editorCtx.format("fontSize", this.data.formats.fontSize + "px");
						this.setData({
							["formats.fontSize"]: 'default',
						});
					}
					else{
						this.editorCtx.format("fontSize", value + "px");
						this.setData({
							["formats.fontSize"]: value,
						});
					}
				}
				break;
			case 'style':
				//加粗/倾斜/下划线
				if(this.data.formats.header==='default'){
					this.editorCtx.format(value, this.data.formats[value]?'':value);
					this.setData({
						["formats."+value]: !this.data.formats[value],
					})
				}
				
				break;
			case 'color':
				//更换字体颜色
				if (value !== this.data.formats.color) {
					this.editorCtx.format("color", value);
					this.setData({
						["formats.color"]: value,
					});
				}
				break;
			case 'align':
				//居左居中居右
				if (value !== this.data.formats.align) {
					this.editorCtx.format("align", value);
					this.setData({
						["formats.align"]: value,
					});
				}
				break;
			case 'list':
				//有序列表无序列表
				if (value !== this.data.formats.list) {
					this.editorCtx.format("list", value);
					this.setData({
						["formats.list"]: value,
					});
				}
				else{
					this.editorCtx.format("list", '');
					this.setData({
						["formats.list"]: '',
					});
				}
				break;
			case 'lineHeight':
				if (value !== this.data.formats.list&&this.data.formats.header==='default'){
					this.editorCtx.format("lineHeight", value);
					this.setData({
						["formats.lineHeight"]: value,
					});
				}
				break;
			case 'undo':
				//撤销
				this.editorCtx.undo();
				break;
			case 'redo':
				//重做
				this.editorCtx.redo();
				break;
			case 'divider':
				//插入分割线
				this.editorCtx.insertDivider()
				break;
			case 'image':
				wx.chooseMedia({
                    mediaType:['image'],
                    sourceType:['album'],
                    success:async (res)=>{
                        const {errMsg,tempFiles}=res
                        if (errMsg==='chooseMedia:ok') {
                            let filePromise=tempFiles.map(async item=>{
                                const response = await that.UploadImgToBase64(item.tempFilePath);
                                let {data}=response;
                                return data
                            })
                            let fileList = [];
                            for (let textPromise of filePromise) {
                                fileList.push(await textPromise)
                            };
                            for(let i=0;i<fileList.length;i++){
                                let reqData={
                                    ImageData:fileList[i]
                                }
                                const resImageUrl = await insertLetterImage(reqData)
                                const {code,data}=resImageUrl;
                                if(code===200){
                                    that.editorCtx.insertImage({
                                        src:data.ImageUrl,
                                        width:'98%',
                                        extClass:'editor--editor-img'
                                    })
                                }
                            }

                        }
                    }
				})
				break;
			case 'shoot':
				wx.chooseMedia({
					mediaType:['image'],
					sourceType:['camera'],
					success:function(){
						
					}
				})
				break;
			case 'header':
				//改变标题
				if (value !== this.data.formats.header){
					this.editorCtx.format("header", value === "default" ? '' : value);
					this.setData({
						["formats.header"]: value,
						["formats.bold"]:false,
						["formats.italic"]:false,
						["formats.underline"]:false,
						["formats.fontSize"]:'default',
						["formats.lineHeight"]:'1.3',
					});
				}
				break;
			default:
				break;
		}
    },
    onBlurField(e){
        let field = e.currentTarget.dataset.field;
        let value = e.detail.value;
        this.VerificationField(field, value);
    },
    onChangeField(e){
        let field = e.currentTarget.dataset.field;
        switch (field) {
          case "to":
            this.setData({
              to: e.detail,
              "error.to_show": false,
            });
            break;
          case "from":
            this.setData({
              from: e.detail,
              "error.from_show": false,
            });
            break;
          default:
            break;
        }
    },
    VerificationField(field, value) {
        let flag = true;
        switch (field) {
          case "to":
            if (value.trim() === "") {
              flag = false;
              this.setData({
                "error.to_show": true,
              });
            }
            break;
          case "from":
            if (value.trim() === "") {
              flag = false;
              this.setData({
                "error.from_show": true,
              });
            }
            break;
          default:
            break;
        }
        return flag;
    },
    UploadImgToBase64(file) {
        return new Promise((resolve,reject) => {
            wx.getFileSystemManager()
                .readFile({
                    filePath: file,
                    encoding: 'base64',
                    success: res => {
                        return resolve(res)
                    },
                    fail(res) {
                        return reject(res)
                    }
                })
        })
    },
    onClickSave(){
        let that=this;
        if (this.VerificationField('to',this.data.to)&&this.VerificationField('from',this.data.from)) {
            this.editorCtx.getContents({
                success:(res)=>{
                    const {errMsg,html}=res;
                    if (errMsg==='ok') {
                        if(html==='<p><br></p>'||html===''){
                            Notify({ type: "danger", message: '请输入情书内容' });
                        }
                        else{
                            let reqData={
                                ToName:that.data.to,
                                FromName:that.data.from,
                                Content:html,
                                Author:app.globalData.userInfo.userSysID
                            }
                            insertLetter(reqData)
                                .then(({code,data,msg})=>{
                                    if (code===200) {
                                        wx.navigateBack({
                                          delta: 1,
                                        })
                                    }
                                    else{
                                        Notify({ type: "danger", message: msg });
                                    }
                                })
                                .catch(()=>{
                                    Notify({ type: "danger", message: '请输入情书内容' });
                                })
                        }
                    }
                }
            })
        }
    }
});
